package server.command;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import util.Command;
import util.Constant;
import util.Control;
import util.Statistically;

public class Put extends Command {
	
	private Statistically rates = new Statistically();
	
	public Put(){super();}
	
	private void sendControlMessenger (Control msg) throws IOException{
		DataOutputStream data_out = new DataOutputStream(getSocket().getOutputStream());
		data_out.flush();
		data_out.writeInt(msg.Code());
	}
	
	private void receiveFile() throws IOException {
		long timeStarted = System.currentTimeMillis();
		
		InputStream in = getSocket().getInputStream();
		DataInputStream data_in = new DataInputStream(in);
		
		String fileName = data_in.readUTF();
		long size_file = data_in.readLong();
		
		System.out.println("Recebendo arquivo: " + fileName + " Tamanho: " + size_file);

		File file = new File("server/"+fileName);
		FileOutputStream out_file = new FileOutputStream(file);

		byte[] buffer = new byte[Constant.SIZE_BUFFER_SERVER];
		int bytes_read = -1;
		long total_read = 0;
		
		while (total_read < size_file){			
			bytes_read = in.read(buffer, 0, Constant.SIZE_BUFFER_SERVER);
			out_file.write(buffer, 0, bytes_read);
			total_read+=bytes_read;
			
			//adicionando informaçoes estatisticas:			
			long rate =  bytes_read / (System.currentTimeMillis() - timeStarted +1);
        	rates.addRate(rate);
        	timeStarted = System.currentTimeMillis();
		}
		
		out_file.close();		
		System.out.println("Arquivo: " + fileName + " Recebido com exito[ media: " + rates.avg + "]");
	}
	
	private void start() throws IOException {
		sendControlMessenger(Control.RECEIVED);
		receiveFile();
		sendControlMessenger(Control.SUCCESS);		
	}
	@Override
	public void execute() {
		try {
			start();
		} catch (IOException e) {
			try {
				sendControlMessenger(Control.FAIL);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally{
			try {
				getSocket().close();
			} catch (IOException e) {				
				e.printStackTrace();
			}
		}
	}
}
